<template>
  <div>
    <custom-table
      ref=" "
      :columns="columns"
      :query="queryParams"
      :row-btn="rowBtn"
      :head-btn="headBtn"
      :head-btn-text="{save:'添加水电费'}"
      :show-head-btn="['flush','save','delete']"
      v-bind="$attrs"
      v-on="listeners"
      :HeadBtnColSize="6"
      :show-row-btn="['delete']"
      @tap-head-btn="onTapHeadBtn"
      @tap-row-btn="onTapRowBtn"
      @row-dblclick="onRowDbClick"
    >
    <template slot="after-head-button">
      <div style="display: flex;">
      <el-upload
    multiple
    :action="fileUrl"
    :headers="headers"
    :limit="limitNum"
    accept=".xls,.xlsx,csv"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-exceed="onExceed"
    :on-success="onSuccess"
    :on-error = "onError"
    :show-file-list="showFileList">
			<!-- <el-button type="primary">导入</el-button> -->
      <el-button :loading="downloadLoadings"  class="filter-item" size="mini" type="primary" icon="el-icon-download">导入水电记录</el-button>
		</el-upload>
  </div>
    </template>
    <template slot="search">
<el-col :span="18" :xs="24">
      <div class="searchFrame">
  <span>待缴费总金额：{{total == ''? 0:total.unPaidTotal}}元</span>
  <span style="margin-left:10px;margin-right:10px;">已缴费总金额：{{total == ''? 0:total.paid}}元</span>
  <span class="demonstration">小区：</span>
  <div style="width: 140px;">
<el-select v-model="value" placeholder="请选择" style="width:100%" @change="selectOk($event)">
    <el-option

      v-for="item in housing"
      :key="item.id"
      :label="item.name"
      :value="item.id">
    </el-option>
  </el-select>
  </div>
    <span class="demonstration">开始时间:</span>
      <div style="width: 140px;">
        <el-date-picker
       style="width:100%;"
          v-model="startTime"
          type="date"
          placeholder="选择日期">
        </el-date-picker>
      </div>
       <span class="demonstration">结束时间:</span>
  <div style="width: 140px;">

    <el-date-picker
    style="width:100%;"
      v-model="lastTime"
      type="date"
      placeholder="选择日期">
    </el-date-picker>
  </div>
    <button class="searchClass" @click="search">搜索</button>
    <el-button :loading="downloadLoading" class="filter-item" type="text" size="mini" icon="el-icon-upload2" @click="handleDownload">导出</el-button>
    </div>

    </el-col>
    </template>
    <!-- <template slot="exportFrame"> -->
    <!-- <el-col :span="11" :xs="12"> -->
       <!-- <div class="searchFrame"> -->

    <!-- </div> -->
    <!-- </el-col> -->
    <!-- </template> -->

    </custom-table>
<el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="35%"
      center>
      <div class="mb10">是否要对{{real_name}}进行现金缴费</div>
      <!-- <div v-if="confirm.input"> -->
        <template>
          <custom-form
            :columns="input"
            :detail = "DetailList"
            :dialog="false"
            :hide-button="true"
            :visible.sync="dialogVisible"
            v-model="confirmFormData"
            @submit="onSubmitConfirm"
          ></custom-form>
        </template>
        <!-- <template v-else>
          <el-input
            v-model="confirmContent"
            :type="typeof confirm.input == 'boolean' ? 'text' : confirm.input"
            :placeholder="confirm.placeholder || ''"
          >
          </el-input>
        </template> -->
      <!-- </div> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="onConfirmCancel">取消</el-button>
        <el-button
          type="primary"
          @click="onConfirmSuccess">确认</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
import tableMixin from '@/utils/mixin/custom-table'
import { showLoading, hideLoading } from '@/utils'
import curd from '@/api/curd'
import { getToken } from '@/utils/auth'
import customForm from '@/views/custom/customForm'
// import mock from '@/utils/mixin/mock'
// var Mock = require('mockjs')
// import { randomNum } from '@/utils'

export default {
  data() {
    return {
      startTime: '',
      lastTime: '',
      housing: [{
        id: 0,
        name: '全部'
      }],
      total: {}, // 缴费总汇
      // options: [{
      //   value: '选项1',
      //   label: '黄金糕'
      // }, {
      //   value: '选项2',
      //   label: '双皮奶'
      // }, {
      //   value: '选项3',
      //   label: '蚵仔煎'
      // }, {
      //   value: '选项4',
      //   label: '龙须面'
      // }, {
      //   value: '选项5',
      //   label: '北京烤鸭'
      // }],
      value: '',
      downloadLoading: false,
      listdata: [], // 导出的数据
      columns: [
        { name: '房号', field: 'room.name', type: 'tag',
          format(col, row) {
            // console.log('row', row)
            if (Object.prototype.hasOwnProperty.call(row, 'room')) {
              return row.room.building.name + row.room.building.building_number + row.room.name
            } else {
              return ''
            }
          }
        },
        { name: '租户', field: 'User.real_name', type: 'tag',
          format(col, row) {
            // console.log('row', row.user_id)
            if (row.user_id == 0) {
              // return row.building.name + row.building.building_number + row.room.name
              return null
            } else {
              return row.User.real_name
            }
          } },
        { name: '月用水量', field: 'm_water', after: '吨', type: 'tag' },
        { name: '水费', field: 'water_price', after: '元', type: 'tag' },
        { name: '月用电量', field: 'm_electricity', after: '度', type: 'tag' },
        { name: '电费', field: 'electricity_price', after: '元', type: 'tag' },
        { name: '日期', field: 'fee_date', type: 'tag'
        // format(col, row) {
        //   let date = row.fee_date
        //   return this.$moment(date).format('YYYY-MM-DD HH:mm:ss')
        // }
        },
        // { name: '状态', field: 'status', label: true, type: this.checkAuth('change') ? 'switch' : 'tag', opts: {} },
        { name: '金额', field: 'fee', after: '元', type: 'tag' },
        { name: '状态', field: 'status', type: 'tag', opts: {}, label: true },
        { name: '添加时间', field: 'create_time' }
      ],

      headBtn: [
        // {
        //   name: '刷新权限',
        //   // 类型
        //   type: 'primary',
        //   // 图标
        //   icon: 'el-icon-refresh-right',
        //   // 权限
        //   auth: this.getFullAuth('flush'),
        //   key: 'flushAuth'
        // }
      ],
      input: [
        { name: '', field: 'building_names', opts: { disabled: true } },
        { name: '', field: 'room_names', opts: { disabled: true } },
        { name: '', field: 'm_waters', opts: { disabled: true } },
        { name: '', field: 'water_prices', opts: { disabled: true } },
        { name: '', field: 'm_electricitys', opts: { disabled: true } },
        { name: '', field: 'electricity_prices', opts: { disabled: true } },
        { name: '', field: 'fee_dates', opts: { disabled: true } },
        { name: '', field: 'fees', opts: { disabled: true } },
        { name: '', field: 'payees', opts: { disabled: true } }

      ],
      dialogVisible: false,
      DetailList: {},
      confirmFormData: {},
      real_name: '',
      fileUrl: process.env.VUE_APP_BASE_API + 'v1/attachment/importWaterEleExcel', // 上传文件的域名地址
      limitNum: 1, // 文件上传个数限制
      fileList: [], // 文件列表
      showFileList: false, // 文件列表是否显示,默认不显示
      headers: {
        'Access-Token': getToken(),
        'X-Requested-With': 'XMLHttpRequest'
      },
      downloadLoadings: false
    }
  },
  components: {
    customForm
  },
  mixins: [
    tableMixin
    //  mock
  ],
  computed: {
    rowBtn() {
      return [
        {
          name: '催收',
          key: 'notice',
          confirm: '确认对{room_name}进行发送催收通知吗？'
          // input: [
          //   { name: '图片', field: 'image', width: 150, required: true }
          // ]
          // show(row) {
          // }
        },
        {
          name: '现金收款',
          key: 'payee',
          // confirm: '确认对{room_name}进行现金缴费吗',
          // input: this.input,
          show(row) {
            // console.log('row', row)
            // return row.pid
            if (row.pid != 0 && row.status == 0) {
              return true
            }
          }
          // detail: this.DetailList
        }
      ]
    }

  },
  props: {},
  filters: {},
  created() {
    var that = this
    that.onLoad()
    setTimeout(() => {
      console.log('table_$attrs', this.$attrs)
      console.log('table_listeners', this.listeners)
    }, 2000)
  },
  methods: {
    // 文件上传类型
    // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet --- 后缀为 .xlsx
    // application/vnd.ms-excel --- 后缀为 .xls或.csv
    // 文件上传之前的钩子,可以做一些验证或限制
    beforeUpload(file) {
      console.log('beforeUpload', file)
      let regExp = file.name.replace(/.+\./, '')
      let lower = regExp.toLowerCase() // 把大写字符串全部转为小写字符串
      let suffix = ['xls', 'xlsx']
      if (suffix.indexOf(lower) === -1) {
        return this.$message.warning('请上传后缀名为 xls、xlsx 的附件 !')
      }
      this.downloadLoadings = true
      // let isLt2M = file.size / 1024 / 1024 < 2
      // if (!isLt2M) {
      //   return this.$message.error('请上传文件大小不能超过 2MB 的附件 !')
      // }
    },
    // 导入表格格式校验,后端已做验证，这个暂时不需要
    // beforeUpload(file) {
    //   // let regExp = file.name.replace(/.+\./, '');
    //   // let suffix = ['xls', 'xlsx'];
    //   // if (suffix.indexOf(regExp.toLowerCase()) === -1) {
    //   // 	return this.$message.warning('请上传后缀名为 xls、xlsx 的附件 !');
    //   // }
    // },
    // 文件超出个数限制时的钩子
    onExceed(files, fileList) {
      console.log('onExceed-files', files)
      console.log('onExceed-fileList', fileList)
      return this.$message.warning(`只能选择${this.limitNum}个文件,当前共选择了${files.length + fileList.length}个`)
    },
    // 文件上传成功时的钩子
    onSuccess(response, file, fileList) {
      console.log('onSuccess', response)
      console.log('onSuccess', file)
      console.log('onSuccess', response)
      this.onTapHeadBtnFlush({})
      this.fileList = []
      this.downloadLoadings = false
    },
    // 文件上传失败时的钩子
    onError() {
      this.fileList = []
      this.downloadLoadings = false
    },
    // 提交现金缴费按钮
    onSubmitConfirm() {

    },
    // 导出数据
    handleDownload() {
      var that = this
      // console.log('startTime', this.startTime)
      // console.log('lastTime', this.lastTime)
      // console.log('housing_id', this.value)
      var data = {}
      if (this.startTime && this.lastTime) {
        var startTime = Date.parse(new Date(that.startTime).toString()) / 1000 // 开始时间戳
        var lastTime = (Date.parse(new Date(that.lastTime).toString()) / 1000) + 86399 // 结束时间戳
        data['startTime'] = startTime
        data['lastTime'] = lastTime
      }
      if (this.startTime) {
        if (!this.lastTime) {
          this.$message({
            message: '请把结束时间也选上',
            type: 'warning'
          })
          return
        }
      }
      if (this.lastTime) {
        if (!this.startTime) {
          this.$message({
            message: '请把开始时间也选上',
            type: 'warning'
          })
          return
        }
      }
      if (this.value != 0) {
        data['housing_id'] = this.value
      }

      // console.log('data', data)
      this.downloadLoading = true
      showLoading('导出中...')
      curd('payRecord').get('getExportList', data).then(res => {
        console.log('获取成功', res.data)
        this.listdata = res.data
        this.down(res.data)
      })
    },
    down(rows) {
      const headers = {
        '房间号': 'room_name',
        '租户': 'real_name',
        '月用水量(吨)': 'm_water',
        '水费': 'water_price',
        '月用电量(度)': 'm_electricity',
        '电费': 'electricity_price',
        '日期': 'fee_date',
        '金额(元)': 'fee',
        '状态': 'status'
      }
      // const filename = '对账单明细'
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // excel是引入文件（也就是@/ventor/Export2Excel）的导出对象
        // 获取所有的数据
        // const { rows } = await curd('check_in').index()
        console.log('rows', rows)
        const data = this.formatJson(headers, rows) // 返回的data就是我们转化后的数据
        excel.export_json_to_excel({
          // 要求转出的表头是中文
          header: Object.keys(headers), // 表头 必填
          data, // //具体数据 必填
          filename: '缴费单信息', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
        this.$notify({
          title: '导出成功',
          // message: '这是一条成功的提示消息',
          type: 'success'
        })
        this.downloadLoading = false
        hideLoading()
        // console.log('excel', excel)
        // 拿到的数据是这种
        //  [{ username: 'xxx', mobile: 'xxx', ... }, { username: 'xxx', mobile: 'xxx', ... }]
        // 要转化的是如下这种
        // header: ['姓名', '手机号', '入职日期', ...]
        // data: [['张三', '138xxxxxxxx', '1992-08-04', ...], ['李四', '135xxxxxxxx', '1992-08-04', ...]]
      })
    },
    formatJson(headers, rows) {
      return rows.map(item => {
        console.log(item)
        return Object.keys(headers).map(k => {
          // if (headers[k] === 'timeOfEntry' || headers[k] === 'correctionTime') {
          //   return formatDate(item[headers[k]]) // 返回格式化之前的时间
          // } else if (headers[k] === 'formOfEmployment') {
          //   return EmployeeEnum.hireType[item.formOfEmployment] ? EmployeeEnum.hireType[item.formOfEmployment] : '未知'
          // }
          return item[headers[k]]
        })
      })
    },
    // 现金缴费
    onTapRowBtnPayee(data) {
      // console.log('data', data)
      var that = this
      this.DetailList = data
      // console.log('list', this.list)
      var list = this.list
      that.real_name = data.room_name
      for (const item of list) {
        if (item.id == data.pid) {
          this.DetailList['building_names'] = '房名: ' + item.room.building.name + item.room.building.building_number + item.room.name
        }
      }
      this.DetailList['room_names'] = '租户: ' + data.room_name
      this.DetailList['m_waters'] = '月用水量: ' + data.m_water
      this.DetailList['water_prices'] = '水费: ' + data.water_price
      this.DetailList['m_electricitys'] = '月用电量: ' + data.m_electricity
      this.DetailList['electricity_prices'] = '电费: ' + data.electricity_price
      this.DetailList['fee_dates'] = '日期: ' + data.fee_date
      this.DetailList['fees'] = '金额: ' + data.fee
      this.DetailList['payees'] = '现金收款人: ' + this.$store.state.user.name
      this.DetailList['payees_id'] = this.$store.state.user.userinfo.id
      // this.DetailList['building_name'] = data.room.building.name + data.room.building.building_number + data.room.name
      that.dialogVisible = true
      console.log('that.dialogVisible', this.$store.state)
    },
    // 取消现金缴费弹窗
    onConfirmCancel() {
      var that = this
      that.dialogVisible = false
      that.DetailList = []
    },
    // 确认现金缴费事件
    onConfirmSuccess(e) {
      var that = this
      console.log('e', that.DetailList)
      var data = {
        id: that.DetailList['id'],
        payees_id: that.DetailList['payees_id'],
        pid: that.DetailList['pid']
      }
      showLoading('修改中...')
      that.curd.post('cashPayProcess', data).then(res => {
        hideLoading()
        // console.log('发送成功', res)
        that.dialogVisible = false
        this.onTapHeadBtnFlush({})
        this.$notify({
          title: '修改成功',
          type: 'success'
          // message: ('发送成功')
        })
      }, hideLoading)
    },
    // 发送催收通知
    onTapRowBtnNotice(data) {
      console.log(data)
      var that = this
      showLoading('发送中...')
      that.curd.post('sendWorthMessage', data).then(res => {
        hideLoading()
        // console.log('发送成功', res)
        this.$notify({
          title: '发送成功',
          type: 'success'
          // message: ('发送成功')
        })
      }, hideLoading)
    },

    // 搜索事件
    search() {
      var that = this

      var startTime = Date.parse(new Date(that.startTime).toString()) / 1000 // 开始时间戳
      var lastTime = (Date.parse(new Date(that.lastTime).toString()) / 1000) + 86399 // 结束时间戳
      if (isNaN(startTime)) {
        alert('请选择开始日期')
        return false
      } else if (isNaN(lastTime)) {
        alert('请选择结束日期')
        return false
      }
      // console.log('我被点击了')
      // that.queryParams = {}
      that.$set(this.params, 'filter[fee_date]', startTime + ',' + lastTime)
      that.$set(this.params, 'op[fee_date]', 'BETWEEN')
      this.$emit('load', { query: this.queryParams })
      that.getTotal(this.queryParams)
    },

    // 初次加载
    onLoad() {
      var that = this
      // console.log('参数', that.params)
      // console.log('我进来了', this.queryParams)
      // 获取小区列表
      that.curd.get('getHousing').then(res => {
        // console.log('全部小区', res)
        for (const item of res.data) {
          that.housing.push(item)
        }
        // console.log('that.housing', that.housing)
      })
      that.getTotal()
    },
    // 获取缴费总汇
    getTotal(queryParams = null) {
      var that = this
      that.curd.get('getTotal', queryParams).then(res => {
        console.log('获取缴费总汇', res)
        if (res.msg == '获取成功') {
          that.total = res.data
        }
      })
    },

    // 选择小区
    selectOk(e) {
      var that = this
      that.$set(this.params, 'room_id', e)
      console.log('我被选中了', this.queryParams)
      this.$emit('load', { query: this.queryParams })
      that.getTotal(this.queryParams)
    },
    // 取消双击编辑功能
    onRowDbClick() {}
    /*
    onLoad() {
      Mock.Random.extend({
        roomType(date) {
          return this.pick(['单间', '一房一厅', '两房一厅', '三房一厅', '豪华套房'])
        },
        area() {
          return randomNum(50, 200)
        },
        amount() {
          return randomNum(500, 2000)
        },
        buildingName(data) {
          return this.pick(['A栋', 'B栋', 'C栋', 'D栋']) + randomNum(1, 999).toString().padStart(3, '0')
        },
        status() {
          return this.pick(['待缴费', '已缴费'])
        },
        roomNo() {
          return '琼花湖' + randomNum(1, 10) + '栋' + randomNum(1, 999).toString().padStart(3, '0')
        }
      })
      var data = Mock.mock({
        // 属性 list 的值是一个数组，其中含有 1 到 10 个元素
        'list|20': [{
          // 属性 id 是一个自增数，起始值为 1，每次增 1
          'id|+1': 1,
          'number': '@roomno',
          'nickname': '@cname',
          'water|1-400': 1,
          'power|1-299': 1,
          'water_num|1-100': 1,
          'power_num|1-299': 1,
          'area': '@area',
          'amount': '@amount',
          'date': '@date',
          'create_time': '@now',
          'status': '@status',
          'room_type': '@roomtype',
          'name': '@buildingname'
        }]
      })

      console.log('mock', data)

      this.setMockData(data)
    }
    */
  }
}
</script>

<style lang="scss">

.startClass{
  // display: flex;
  // // margin-left: 50px;
  // align-items: center;
  // text-align: center;
  // justify-content: center;
  // padding-top: 5px;
  // width: 50px;
  // align-items: center;
  // margin-left: 50px;
  // width: 20px;
  // position: fixed;
  // top: 98px;
  // // margin: -25px -15px 0;
  // left: 65%;
  // z-index: 9;
  // margin-left: 50px;
}
.demonstration{
    margin-left: 5px;
    color: #8492a6;
    font-size: 14px;
    // width: 20px;
  // padding:15px
  // margin-top: 5px;
  // color: #f4f4f5;
}
.lastClass{
  // display: flex;
  // align-items: center;
  // text-align: center;
  // justify-content: center;
  // margin-right: 50px;
  // margin-right: 50px;
  // position: fixed;
  // //
  // top: 98px;
  // left: 78%;
  // z-index: 9;
}
.searchClass{
  padding: 7px 15px;
  font-size: 12px;
  margin-left: 10px;
  border-radius: 3px;
  margin-right: 20px;
  width: 100px;
  // position: fixed;
  // top: 98px;
  // left: 90%;
  // z-index: 9;
  // display: flex;
  // align-items: center;
  // justify-content: center;
  color: #FFFFFF;
  background-color: #1890ff;
  // border-color: #1890ff;
}
.searchFrame{
  display: flex;
  width: 100%;
  align-items: center;
  justify-content:flex-end;
  // padding: 15px;
  // flex-direction: row-reverse;
  // height: 90px;
  // padding-right: 20px;
  // padding: 10px 20px;
}
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  // .demonstrations {
  //   display: block;
  //   color: #8492a6;
  //   font-size: 14px;
  //   margin-bottom: 20px;
  // }
   .mb10 {
    margin-bottom: 10px;
  }
</style>
